package tool.zyk.protocol;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.util.concurrent.DefaultPromise;
import lombok.extern.slf4j.Slf4j;
import tool.zyk.consts.RpcCommonConst;
import tool.zyk.stardand.RpcResponse;
import tool.zyk.utils.LogUtil;

import java.util.List;
import java.util.Objects;

/**
 * @author feite.zyk
 * @time 2024/2/1 13:47
 * @description
 */
@Slf4j
public class ProtocolResponseM2MDecoder extends MessageToMessageDecoder<RpcResponse> {
    private final DefaultPromise<RpcResponse> defaultPromise;


    public ProtocolResponseM2MDecoder(DefaultPromise<RpcResponse> rpcResponseDefaultPromise) {
        this.defaultPromise = rpcResponseDefaultPromise;
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, RpcResponse rpcResponse, List<Object> list) throws Exception {
        try {
            log.info("response decode->{}", rpcResponse);
            if (Objects.equals(rpcResponse.getCode(), RpcCommonConst.StatusCode.SUCCESS_CODE)) {
                defaultPromise.setSuccess(rpcResponse);
            } else {
                defaultPromise.setFailure(new RuntimeException(rpcResponse.getMsg()));
            }
            channelHandlerContext.channel().close();
        } catch (Throwable throwable) {
            LogUtil.printErrorLog(throwable);
            throw new RuntimeException(throwable);
        }
    }
}
